/*******************************************************************************
 * Copyright (c) 2008 Sylvain Sicard.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Sylvain Sicard - initial API and implementation
 ******************************************************************************/
package fr.jade.fraclite.control.lifecycle;

import org.objectweb.fractal.api.Component;
import org.objectweb.fractal.api.NoSuchInterfaceException;
import org.objectweb.fractal.api.control.ContentController;
import org.objectweb.fractal.api.control.IllegalLifeCycleException;
import org.objectweb.fractal.api.control.LifeCycleController;
import org.objectweb.fractal.api.factory.InstantiationException;
import org.objectweb.fractal.util.Fractal;

import fr.jade.fraclite.InitializationContext;
import fr.jade.fraclite.api.Controller;

public class BasicLifeCycleController implements Controller, LifeCycleController {

	protected String state = LifeCycleController.STOPPED;
	protected ContentController cc = null;
	protected LifeCycleController innerImpl = null;

	public void initFcController (final InitializationContext ic) throws InstantiationException {
	  if (ic.content instanceof LifeCycleController){
      innerImpl = (LifeCycleController)ic.content;
    }
	  try{
      cc = (ContentController)ic.getInterface("content-controller");
	  }catch(InstantiationException ignored){}
    state = LifeCycleController.STOPPED;
  }
	
	public String getFcState() {
	  if(innerImpl == null){
	    return state;
	  }else{
	    return innerImpl.getFcState();
	  }
	}

	public void startFc() throws IllegalLifeCycleException {
	  if(state.equals(LifeCycleController.STOPPED)){
  		if(cc != null){
    		for(Component sub : cc.getFcSubComponents()){
    			try{
    				LifeCycleController lcc = Fractal.getLifeCycleController(sub);
    				lcc.startFc();
    			}catch(NoSuchInterfaceException ignored){ }
    		}
  		}
  		if(innerImpl != null){
  		  innerImpl.startFc();
  		}
  		state=LifeCycleController.STARTED;
  	}
	}

	public void stopFc() throws IllegalLifeCycleException {
	  if(state.equals(LifeCycleController.STARTED)){
  	  if(cc != null){
    		for(Component sub : cc.getFcSubComponents()){
    			try{
    				LifeCycleController lcc = Fractal.getLifeCycleController(sub);
    				lcc.stopFc();
    			}catch(NoSuchInterfaceException ignored){ }
    		}
  	  }
  	  if(innerImpl != null){
  	    innerImpl.stopFc();
  	  }
  	  state=LifeCycleController.STOPPED;
	  }
	}

}
